from PIL import Image
import pytesseract
import os

# 字库
lang = 'eng+chi_simp'
# lang = 'eng+chi_sim'
# lang = 'melang'

# 图片
# image = Image.open(r'.\pic\cut_1112101839-004.png')
# image = Image.open(r'.\pic\111.png')
# image = Image.open(r'.\pic\222.png')

# image = Image.open(r'.\pic\car.jpg') # 原图，只能识别数字

# 测试什么样的图片效果最好
# image = Image.open(r'.\pic\car2.jpg')  # 白底黑字(手写截图测试)，效果最好
# image = Image.open(r'.\pic\car3.jpg') # pillow，黑底白字，识别不出来
# image = Image.open(r'.\pic\car4.jpg')  # 黑底白字，只能识别数字

# 第一步，二值化
# image = Image.open(r'.\pic\pillow\car_a.jpg')  # 图片二值化，黑底白字

# 第二步，反色
# img_path = r'.\pic\pillow\cut.jpg'
# img_path = r'.\pic\pillow\cut_1112101839-007_inverse_230.jpg'
# img_path = r'.\pic\pillow\cut_1112101839-007_inverse_235.jpg'
# img_path = r'.\pic\pillow\cut_1112101839-027_inverse_230.jpg'
img_path = r'.\pic\pillow\cut_1112101839-027_inverse_235.jpg'
# img_path = r'.\pic\pillow\cut_1112101839-027_inverse_237.jpg'
# img_path = r'.\pic\pillow\cut_1112101839-027_inverse_240.jpg'
# 灰度界限230比240识别更准确，但是当230时 图片027 背景无法去除
# 取了一个中值235效果还不错
image = Image.open(img_path)  # 图片二值化,反色，白底黑字

text = pytesseract.image_to_string(image, lang)
print(text + "\n")

# 识别文件夹所有图片
# file_path = r'C:\Users\bingwa\Desktop\pic\car' + '\\'
# file_path = r'.\car\cut' + '\\'
# pic_list = os.listdir(file_path)
# for img in pic_list:
#     img_path = file_path + img
#     print(img_path)
#     text = pytesseract.image_to_string(Image.open(img_path))
#     print(text + "\n")
